//
//  ESToolbarView.m
//  
//
//  Created by fuyoufang on 15/10/15.
//
//

#import "ESToolbarView.h"
#import "XHMessageTextView.h"
#import "DXRecordView.h"

@interface ESToolbarView () <UITextViewDelegate>

/** 上一次inputTextView的contentSize.height */
@property (assign, nonatomic) CGFloat previousTextViewContentHeight;

@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;
@property (weak, nonatomic) IBOutlet UIButton *styleChangeButton;
@property (weak, nonatomic) IBOutlet UIButton *moreButton;
@property (weak, nonatomic) IBOutlet UIButton *faceButton;

/** 录音按钮 */
@property (weak, nonatomic) IBOutlet UIButton *recordButton;
@property (assign, nonatomic) MessageInputStyle inputStyle;

@property (assign, nonatomic) CGFloat maxTextViewHeight;
- (IBAction)styleChangeButtonClick:(id)sender;
- (IBAction)faceButtonClick:(id)sender;
- (IBAction)moreButtonClick:(id)sender;

@end

@implementation ESToolbarView
#pragma mark - 懒加载

#pragma mark - setter
- (void)setMaxTextViewHeight:(CGFloat)maxTextViewHeight {
    if (maxTextViewHeight > kInputTextViewMaxHeight) {
        maxTextViewHeight = kInputTextViewMaxHeight;
    }
    _maxTextViewHeight = maxTextViewHeight;
}

#pragma mark - 系统方法
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.faceButton.selected = NO;
        self.styleChangeButton.selected = NO;
        self.moreButton.selected = NO;
        self.inputStyle = MessageInputStyleKeyboard;
        [self.recordButton setImage:[[UIImage imageNamed:@"chatBar_recordBg"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateNormal];
        [self.recordButton setImage:[[UIImage imageNamed:@"chatBar_recordSelectedBg"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateHighlighted];
        
        [self setupMessageTextView];
        self.previousTextViewContentHeight = [self getTextViewContentH:self.messageTextView];
        [self setupRecordButton];
    }
    return self;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    self.faceButton.selected = NO;
    self.styleChangeButton.selected = NO;
    self.moreButton.selected = NO;
    self.inputStyle = MessageInputStyleKeyboard;
    [self.recordButton setImage:[[UIImage imageNamed:@"chatBar_recordBg"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateNormal];
    [self.recordButton setImage:[[UIImage imageNamed:@"chatBar_recordSelectedBg"] stretchableImageWithLeftCapWidth:10 topCapHeight:10] forState:UIControlStateHighlighted];
    
    [self setupMessageTextView];
    self.previousTextViewContentHeight = [self getTextViewContentH:self.messageTextView];
    [self setupRecordButton];

}

+ (instancetype)toolbarView {
    ESToolbarView *toolbarView = [[[NSBundle mainBundle] loadNibNamed:@"ESToolbarView" owner:nil options:nil] lastObject];
    return toolbarView;
}
/**
 *  默认高度
 *
 *  @return 默认高度
 */
+ (CGFloat)defaultHeight {
    return kVerticalPadding * 2 + kInputTextViewMinHeight;
}

- (BOOL)endEditing:(BOOL)force {
    self.moreButton.selected = NO;
    self.faceButton.selected = NO;
    return [super endEditing:force];
}
#pragma mark - 初始化
- (void)setupRecordButton {
    self.recordButton.hidden = YES;
    [self.recordButton addTarget:self action:@selector(recordButtonTouchDown) forControlEvents:UIControlEventTouchDown];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.recordButton addTarget:self action:@selector(recordDragOutside) forControlEvents:UIControlEventTouchDragExit];
    [self.recordButton addTarget:self action:@selector(recordDragInside) forControlEvents:UIControlEventTouchDragEnter];
    self.recordButton.hidden = YES;
}

- (void)setupMessageTextView {
    self.messageTextView.scrollEnabled = YES;
    self.messageTextView.returnKeyType = UIReturnKeySend;
    self.messageTextView.enablesReturnKeyAutomatically = YES; // UITextView内部判断send按钮是否可以用
    self.messageTextView.placeHolder = NSLocalizedString(@"message.toolBar.inputPlaceHolder", @"input a new message");
    self.messageTextView.delegate = self;
    self.messageTextView.backgroundColor = [UIColor clearColor];
    self.messageTextView.layer.borderColor = [UIColor colorWithWhite:0.8f alpha:1.0f].CGColor;
    self.messageTextView.layer.borderWidth = 0.65f;
    self.messageTextView.layer.cornerRadius = 6.0f;
}

#pragma mark - 其他方法
/**
 *  获取 UITextView 的高度
 */
- (CGFloat)getTextViewContentH:(UITextView *)textView{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        return ceilf([textView sizeThatFits:textView.frame.size].height);
    } else {
        return textView.contentSize.height;
    }
}


- (void)willShowInputTextViewToHeight:(CGFloat)toHeight {
    if (toHeight < kInputTextViewMinHeight) {
        toHeight = kInputTextViewMinHeight;
    }
    if (toHeight > self.maxTextViewHeight) {
        toHeight = self.maxTextViewHeight;
    }
    
    if (toHeight == self.previousTextViewContentHeight) {
        return;
    }
    self.previousTextViewContentHeight = toHeight;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0) {
#warning TODO 为什么除以2
        [self.messageTextView setContentOffset:CGPointMake(0.0f, (self.messageTextView.contentSize.height - self.messageTextView.frame.size.height) / 2) animated:YES];
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(toolbarView:needChangeToHeight:)]) {
        [self.delegate toolbarView:self needChangeToHeight:(toHeight + kVerticalPadding * 2)];
    }
}

#pragma mark - 按钮事件
- (IBAction)styleChangeButtonClick:(UIButton *)sender {
    self.styleChangeButton.selected = !self.styleChangeButton.selected;
    if (self.styleChangeButton.selected) {
        self.inputStyle = MessageInputStyleRecord;
        self.faceButton.selected = NO;
        self.moreButton.selected = NO;
        [self.messageTextView resignFirstResponder];
#warning TODO 调整高度（输入文字和录音下的高度可能不同）
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.recordButton.hidden = NO;
            self.messageTextView.hidden = YES;
        } completion:^(BOOL finished) {}];
        
    } else {
        self.inputStyle = MessageInputStyleKeyboard;
        [self.messageTextView becomeFirstResponder];
#warning TODO 调整高度（输入文字和录音下的高度可能不同）
        //键盘也算一种底部扩展页面
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.recordButton.hidden = YES;
            self.messageTextView.hidden = NO;
        } completion:^(BOOL finished) {}];
    }

    if ([self.delegate respondsToSelector:@selector(toolbarView:didChangedMessageInputStyle:)]) {
        [self.delegate toolbarView:self didChangedMessageInputStyle:self.inputStyle];
    }
}

- (IBAction)faceButtonClick:(id)sender {
    self.faceButton.selected = !self.faceButton.selected;
    if (self.faceButton.selected) {
        if (self.inputStyle == MessageInputStyleRecord) {
            [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.recordButton.hidden = YES;
                self.messageTextView.hidden = NO;
            } completion:^(BOOL finished) {}];
        }

        self.inputStyle = MessageInputStyleFacial;
        self.styleChangeButton.selected = NO;
        self.moreButton.selected = NO;
        [self.messageTextView resignFirstResponder];
    } else {
        self.inputStyle = MessageInputStyleKeyboard;
        [self.messageTextView becomeFirstResponder];
    }
    if ([self.delegate respondsToSelector:@selector(toolbarView:didChangedMessageInputStyle:)]) {
        [self.delegate toolbarView:self didChangedMessageInputStyle:self.inputStyle];
    }
}

- (IBAction)moreButtonClick:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        if (self.inputStyle == MessageInputStyleRecord) {
            [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                self.recordButton.hidden = YES;
                self.messageTextView.hidden = NO;
            } completion:^(BOOL finished) {}];
        }
        self.inputStyle = MessageInputStyleMore;
        self.faceButton.selected = NO;
        self.styleChangeButton.selected = NO;
        [self.messageTextView resignFirstResponder];
        
    } else {
        self.inputStyle = MessageInputStyleKeyboard;
        self.styleChangeButton.selected = NO;
        [self.messageTextView becomeFirstResponder];
    }
    if ([self.delegate respondsToSelector:@selector(toolbarView:didChangedMessageInputStyle:)]) {
        [self.delegate toolbarView:self didChangedMessageInputStyle:self.inputStyle];
    }
}

#pragma mark 录音按钮
- (void)recordButtonTouchDown {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didStartRecordingVoiceAction:)]) {
        [self.delegate didStartRecordingVoiceAction:self];
    }
}

- (void)recordButtonTouchUpOutside {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didCancelRecordingVoiceAction:)]) {
        [self.delegate didCancelRecordingVoiceAction:self];
    }
}

- (void)recordButtonTouchUpInside {
    if ([self.delegate respondsToSelector:@selector(didFinishRecoingVoiceAction:)]) {
        [self.delegate didFinishRecoingVoiceAction:self];
    }
}

- (void)recordDragOutside {
    if ([self.delegate respondsToSelector:@selector(didDragOutsideAction:)]) {
        [self.delegate didDragOutsideAction:self];
    }
}

- (void)recordDragInside {
    if ([self.delegate respondsToSelector:@selector(didDragInsideAction:)]) {
        [self.delegate didDragInsideAction:self];
    }
}

#pragma mark - UITextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if ([self.delegate respondsToSelector:@selector(toolbarView:inputTextViewWillBeginEditing:)]) {
        [self.delegate toolbarView:self inputTextViewWillBeginEditing:textView];
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([self.delegate respondsToSelector:@selector(toolbarView:inputTextViewDidBeginEditing:)]) {
        [self.delegate toolbarView:self inputTextViewDidBeginEditing:textView];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        if ([self.delegate respondsToSelector:@selector(toolbarView:inputTextViewDidEnterReturn:)]) {
            [self.delegate toolbarView:self inputTextViewDidEnterReturn:textView];
            
        }
        self.messageTextView.text = @"";
        [self willShowInputTextViewToHeight:[self getTextViewContentH:self.messageTextView]];
        return NO;
    }
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if ([self.delegate respondsToSelector:@selector(toolbarView:inputTextViewDidEndEditing:)]) {
        [self.delegate toolbarView:self inputTextViewDidEndEditing:textView];
    }
}

- (void)textViewDidChange:(UITextView *)textView {
    [self willShowInputTextViewToHeight:[self getTextViewContentH:textView]];
}

@end
